import request from "./request.js";
import config from "./config.js";
import common from "./common.js";

function init(shareId) {
	const openid = common.getOpenid();
	if(openid) {
		loadShopData();
	} else {
		uni.login({
			success:function(res){
				const query = {code: res.code, shareId: shareId, anonymousCode: res.anonymousCode};
				//只用上传code然后获取openid即可
				request.get("/auth/getUserInfo", query, {}, true).then((result) => {
					// console.log("=====getOpenid result====>>>", result)
					if(result.data) {
						common.setCustomer(result.data);
						common.setOpenid(result.data.openid);
					}
					loadShopData();
				})
			}
		})
	}
}

function loadShopData() {
	request.get("/shop/queryOwnShop", {}).then((res) => {
		console.log("======55555=====>>", res);
		// const shopList = res.shopList;
		const isBoss = res.isBoss;
		const isWorker = res.isWorker;
		// if(shopList.length <= 0) {
		if(isBoss || isWorker) { //如果是老板或员工，都需要跳转到首页
			// console.log('------没有店铺----')
			uni.switchTab({
				url: "/pages/index/index"
			})
		} else {
			uni.redirectTo({
				url: "/pages/shop/addIndex"
			})
		}
	})
}

function initOpenid(shareId) {
	const openid = common.getOpenid();
	console.log("--------check openid--", openid)
	if(!openid) {
		uni.login({
			success:function(res){
				const query = {code: res.code, shareId: shareId, anonymousCode: res.anonymousCode};
				//只用上传code然后获取openid即可
				request.get("/auth/getUserInfo", query).then((result) => {
					console.log("=====getOpenid result====>>>", result)
					if(result.data) {
						common.setCustomer(result.data);
						common.setOpenid(result.data.openid);
					}
				})
			}
		})
	}
}

export default {
	init: init,
	initOpenid: initOpenid,
}